<template>
  <div style="width: 95%;margin-left:3%;">
    <h2 style="text-align: left; ">警报检测</h2>

    <el-row type="flex" :gutter="20" style="width: 100%; flex-wrap: wrap">
      <!-- <el-col v-for="(item,index) in alertNameArr" :key="index" :span="7.5">
        <el-input style="width: 200px" :value="item" disabled />
        <el-button style="margin:0 10px;" @click="deleteAlertItem(item)">启动</el-button>
      </el-col> -->
      <el-col :span="8">
        <el-table :data="alertList" max-height="580px" border style="margin-top: 10px;">
          <el-table-column label="警报名" prop="alertname" width="100" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作" width="80" prop="scope">
            <template slot-scope="scope">
              <el-button
                v-if="!alertList[scope.$index]['runstate']"
                size="mini"
                type="primary"
                @click="runOrStopAlert(scope.$index, scope.row, true)"
              >启动
              </el-button>
              <el-button
                v-if="alertList[scope.$index]['runstate']"
                size="mini"
                type="danger"
                @click="runOrStopAlert(scope.$index, scope.row, false)"
              >关闭
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="16">
        <el-table :data="messageList" max-height="580px" border style="margin-top: 10px;">
          <el-table-column label="警报名" prop="alertname" width="100" />
          <el-table-column label="发生时间" prop="time" width="220" />
          <el-table-column label="内容" prop="content" />
        </el-table>
      </el-col>
    </el-row>
  </div>
</template>

<script>
// import { Message } from 'element-ui'
import { formatTime } from '@/utils/util.js'
// import axios from 'axios'
import axiosservice from '@/utils/CommonData.js'

export default {
  name: 'AlertMessage',
  data() {
    return {
      alertList: [],
      messageList: this.DataForAlertMessage.messageList,
      timerId: this.DataForAlertMessage.timerId
    }
  },
  mounted() {
    // if (!this.DataForAlertMessage.haveData) {
    //   console.log(this.DataForAlertMessage.haveData)
    this.getAlertList()
    //   this.DataForAlertMessage.haveData = true
    // } else {
    //   console.log('altermessage读取全局数据')
    // }
    console.log(this.DataForAlertMessage)
    if (this.DataForAlertMessage.timerId == null) { // 刷新页面后重新启动定时器
      this.getAllAlertMessage()
      // this.DataForAlertMessage.timerId = setInterval(this.getNewAlertMessage, 3000) // 改为请求所有警报后再启动定时器
    }
    // this.timerId = setInterval(this.getAlertMessage, 3000)
  },
  methods: {
    getAlertList() { // 这里用来查询时间间隔
      // axios.get('/getallalert')
      axiosservice({
        url: '/getallalert',
        method: 'get'
      })
        .then((res) => {
          if (res.status == 200) {
            this.alertList.splice(0, this.alertList.length) // 先清空列表
            for (const i of res.data.data) {
              this.alertList.push(i)
            }
            // this.alertList = res.data.data //这会改变对象地址，不可行
            for (const i of this.alertList) {
              if (i.state == 'true') {
                this.$set(i, 'runstate', true)
              } else {
                this.$set(i, 'runstate', false)
              }
              // i['runstate'] = false //这会导致没有set和get方法，导致视图不更新，不可行
            }
            console.log(this.alertList)// res.data是获取到的json数据
          }
        })
        .catch((error) => {
          console.log(error)
          this.$message.error('获取警报数据失败!')
        })
    },
    getNewAlertMessage() {
      axiosservice({
        url: '/getnewmessage',
        method: 'get'
      })
        .then((res) => {
          if (res.status == 200) {
            if (res.data.code == 200) { //
              const resdata = res.data.data
              console.log(resdata)
              var i = 0
              if (resdata.length > 5) {
                for (i = 0; i < resdata.length; i++) {
                  const obj = resdata[i] // 不需要字符串转对象
                  const tempObj = {
                    alertname: obj.alertname,
                    time: formatTime(obj.time),
                    content: obj.content
                  }
                  this.messageList.unshift(tempObj)// 头插入
                }
                this.$message({
                  message: '有5条以上的新警报发生，请在警报检测页面查看',
                  type: 'warning'
                })
              } else {
                for (i = 0; i < resdata.length; i++) {
                  const obj = resdata[i] // 不需要字符串转对象
                  const level = obj.level
                  const tempObj = {
                    alertname: obj.alertname,
                    time: formatTime(obj.time),
                    content: obj.content
                  }
                  this.messageList.unshift(tempObj)// 头插入
                  if (level == 'a') {
                    this.$message({
                      message: '警报:' + tempObj.alertname + ' ' + tempObj.content,
                      type: 'error'
                    })
                  } else if (level == 'b') {
                    this.$message({
                      message: '警报:' + tempObj.alertname + ' ' + tempObj.content,
                      type: 'warning'
                    })
                  } // 等于c时不提示，只插入列表
                }
              }
            } else {
              console.log(res.data)
            }
          }
        })
        .catch((error) => {
          console.log(error)
          this.$message.error('获取数据失败!')
        })
    },
    getAllAlertMessage() {
      axiosservice({
        url: '/getallmessage',
        method: 'get'
      })
        .then((res) => {
          this.DataForAlertMessage.timerId = setInterval(this.getNewAlertMessage, 3000)
          if (res.status == 200) {
            if (res.data.code == 200) { //
              const resdata = res.data.data
              for (const i of resdata) { // 首次加载，全部插入，不报警
                if (i != '{}') {
                  const obj = JSON.parse(i) // 字符串转对象
                  const tempObj = {
                    alertname: obj.alertname,
                    time: formatTime(parseInt(obj.time)),
                    content: obj.content
                  }
                  this.messageList.unshift(tempObj)// 头插入
                }
              }
              // this.lasttime = JSON.parse(resdata[resdata.length - 1]).time
            } else {
              console.log(res.data)
            }
          }
        })
        .catch((error) => {
          // this.DataForAlertMessage.timerId = setInterval(this.getNewAlertMessage, 3000) // 无论成功失败都要启动定时器
          console.log(error)
          this.$message.error('获取数据失败!')
        })
    },

    runOrStopAlert(index, row, state) {
      axiosservice({
        url: '/changestate',
        method: 'get',
        params: {
          state,
          alertname: row.alertname
        }
      })
        .then((res) => {
          if (res.status == 200) {
            if (res.data.code == 200) { // 警报
              this.$set(this.alertList[index], 'runstate', state)
              this.$message({
                message: '修改成功',
                type: 'warning'
              })
            } else if (res.data.code == 0) {
              this.$message({
                message: '修改失败',
                type: 'warning'
              })
            } else {
              console.log(res.data)
            }
          }
        })
        .catch((error) => {
          console.log(error)
          this.$message.error('获取数据失败!')
        })
    }
    // StopAlert(index, row) {
    //   clearInterval(this.timerIdList[index])
    //   this.timerIdList[index] = null
    //   this.$set(this.alertList[index], 'runstate', false)
    //   // this.alertList[index]['runstate'] = false
    //   console.log('stop', index, row)
    // }
  }
}
</script>

<style scoped>

</style>
